/*
 * @Description:
 * @Date: 2021-10-27 15:42:02
 * @LastEditTime: 2022-04-02 11:12:32
 * @FilePath: /vue3-element-plus/src/utils/tools/index.ts
 * @Author: Devin
 */

//验证邮箱
export const isEmail = (s: string) => {
  return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(s);
};

//验证手机号码

export const isMobile = (s: string) => {
  return /^[0-9]{8,11}$/.test(s);
};

//验证密码

export const isPass = (s: string) => {
  const PASS_REG =
    /((^(?=.*[a-z])(?=.*[A-Z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[A-Z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*\W)[\da-zA-Z\W]{8,32}$)|(^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-Z\W]{8,32}$))/;
  return PASS_REG.test(s);
};

// 3.电话号码

export const isPhone = (s: string) => {
  return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s);
};

// 4.是否url地址

export const isURL = (s: string) => {
  return /^http[s]?:\/\/.*/.test(s);
};

// 5.是否字符串

export const isString = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'String';
};

// 6.是否数字

export const isNumber = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Number';
};

// 7.是否boolean

export const isBoolean = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean';
};

// 8.是否函数

export const isFunction = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Function';
};

// 9.是否为null

export const isNull = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Null';
};

// 10.是否undefined

export const isUndefined = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined';
};

// 11.是否对象

export const isObj = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Object';
};

// 12.是否数组

export const isArray = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Array';
};

// 13.是否时间

export const isDate = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Date';
};

// 14.是否正则

export const isRegExp = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp';
};

// 15.是否错误对象

export const isError = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Error';
};

// 16.是否Symbol函数

export const isSymbol = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Symbol';
};

// 17.是否Promise对象

export const isPromise = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Promise';
};

// 18.是否Set对象

export const isSet = (o: any) => {
  return Object.prototype.toString.call(o).slice(8, -1) === 'Set';
};

export const ua: any = navigator.userAgent.toLowerCase();

// 19.是否是微信浏览器

export const isWeiXin = () => {
  return ua.match(/microMessenger/i) == 'micromessenger';
};

// 20.是否是移动端

export const isDeviceMobile = () => {
  return /android|webos|iphone|ipod|balckberry/i.test(ua);
};

// 21.是否是QQ浏览器

export const isQQBrowser = () => {
  return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i);
};

// 22.是否是爬虫

export const isSpider = () => {
  return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider|scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sogou orion spider/.test(
    ua
  );
};
/**
 * @description: 封装sessionStorage和localStorage
 * @param {*}
 * @return {*}
 */
export const storage = {
  setLocal: (key: any, value: any) => {
    if (isArray(value) || isObj(value) || isBoolean(value)) {
      window.localStorage.setItem(key, JSON.stringify(value));
    } else {
      window.localStorage.setItem(key, value);
    }
  },
  getLocal: (key: string) => {
    let value = window.localStorage.getItem(key);
    if (value) {
      return JSON.parse(value);
    } else {
      return value;
    }
  },
  clearOneLocal: (key: string) => {
    window.localStorage.removeItem(key);
  },
  clearAllLocal: () => {
    // indexDBStore 不清除
    const indexDBStore = storage.getLocal('indexDBStore');
    window.localStorage.clear();
    storage.setLocal('indexDBStore', JSON.stringify(indexDBStore));
  },
  setSession: (key: string, value: any) => {
    //正常设置，会覆盖原值
    if (isArray(value) || isObj(value) || isBoolean(value)) {
      window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(JSON.stringify(value))));
    } else {
      window.sessionStorage.setItem(key, window.btoa(window.encodeURIComponent(value)));
    }
    // window.sessionStorage.setItem(key, JSON.stringify(value))
  },
  appendSession: (key: string, value: any) => {
    //追加赋值，不会覆盖原值
    let getValue = window.sessionStorage.getItem(key);
    if (getValue) {
      let oldValue = JSON.parse(getValue);
      let newValue = Object.assign(oldValue, value);
      window.sessionStorage.setItem(key, JSON.stringify(newValue));
    } else {
      window.sessionStorage.setItem(key, JSON.stringify(value));
    }
  },
  getSession: (key: string) => {
    //需要判断取值格式，如果是string或者undefined，不能JSON.PARSE()
    let value = window.sessionStorage.getItem(key);
    if (!value) {
      return value;
    } else {
      try {
        if (
          isArray(JSON.parse(window.decodeURIComponent(window.atob(value)))) ||
          isObj(JSON.parse(window.decodeURIComponent(window.atob(value))))
        ) {
          return JSON.parse(window.decodeURIComponent(window.atob(value)));
        } else {
          if (window.decodeURIComponent(window.atob(value)) == 'true') {
            return true;
          } else if (window.decodeURIComponent(window.atob(value)) == 'false') {
            return false;
          } else {
            return window.decodeURIComponent(window.atob(value));
          }
        }
      } catch (e) {
        return window.decodeURIComponent(window.atob(value));
      }
    }
  },
  clearOneSession: (key: string) => {
    window.sessionStorage.removeItem(key);
  },
  clearAllSession: () => {
    window.sessionStorage.clear();
  }
};

/**
 * @description: 如果只有三位的值，需变成六位，如：#fff => #ffffff
 * @param  {*}
 * @return {*}
 * @param {string} hex
 * @param {number} opacity
 */
export const colorRgba = function (hex: string, opacity: number = 1) {
  let res = '';
  res = parseInt(hex[2] + hex[3], 16) + ', ' + parseInt(hex[4] + hex[5], 16) + ', ' + parseInt(hex[6] + hex[7], 16);
  return `rgba(${res}, ${opacity})`;
};

/**
 * @description: 随机生成整数
 * @return {*} number
 * @param {number} min 最小值
 * @param {number} max 最大值
 */
export const random = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min)) + min;
};

/**
 * @description: 初始化主题色
 * @param {*}
 * @return {*}
 * @default:
 */
export const initThemeColor = (): void => {
  let color = storage.getSession('main-color');
  if (color) {
    setRootColor(color);
  }
};

/**
 * @description: 设置主题色
 * @param {string} color
 * @return {*}
 * @default:
 */
export const setThemeColor = (color: string): void => {
  setRootColor(color);
  storage.setSession('main-color', color);
};

/**
 * @description: 设置css变量
 * @param {string} color
 * @return {*}
 * @default:
 */
function setRootColor(color: string): void {
  let styles: any = document.documentElement;
  styles.style.setProperty('--cc-main-color', `rgba(${color},1)`);
  styles.style.setProperty('--cc-menu-active-back-color', `rgba(${color},0.15)`);
  styles.style.setProperty('--cc-menu-active-hover-back-color', `rgba(${color},0.05)`);
  styles.style.setProperty('--cc-button-hover-bg-color', `rgba(${color},0.2)`);
  styles.style.setProperty('--cc-button-hover-border-color', `rgba(${color},0.3)`);
  styles.style.setProperty('--cc-button-hover-text-color', `rgba(${color},0.7)`);
}

/**
 * @description: 获取vue原型的方法
 * @param {*}
 * @return {*} vue实例
 * @default:
 */
export function getVueGlobalProperties(data: any): any {
  return data?.appContext?.config.globalProperties;
}

export interface ScrollToErrorField {
  className: string;
  block: any;
  behavior: any;
}
/**
 * @description:
 * @param className 滚动到的class位置
 * @param block 值有start,center,end，nearest，当前显示在视图区域中间
 * @param behavior 值有auto、instant,smooth，缓动动画（当前是慢速的）
 * @return {*}
 */
export const scrollToErrorField = ({ className, block = 'center', behavior = 'smooth' }: ScrollToErrorField) => {
  const theDom = document.getElementsByClassName(className);
  theDom[0].scrollIntoView({block,behavior});
};
